package com.example.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.TTLConstants;
import com.example.common.core.domain.TableDataInfo;
import com.example.common.core.enums.ExamListType;
import com.example.common.core.enums.ResultCode;
import com.example.common.core.exception.ServiceException;
import com.example.common.security.utils.ThreadLocalUtil;
import com.example.friend.domain.UserExam;
import com.example.friend.domain.exam.Exam;
import com.example.friend.domain.exam.dto.ExamDTO;
import com.example.friend.domain.exam.dto.ExamQueryDTO;
import com.example.friend.domain.exam.vo.ExamVO;
import com.example.friend.manger.ExamCacheManager;
import com.example.friend.mapper.exam.ExamMapper;
import com.example.friend.mapper.user.UserExamMapper;
import com.example.friend.service.user.IUserExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamServiceImpl implements IUserExamService {

    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private UserExamMapper userExamMapper;
    @Autowired
    private ExamCacheManager examCacheManger;

    //报名竞赛
    @Override
    public Integer enter(ExamDTO examDTO) {




        //先去数据库查询对应的exam，检验是否存在
        Exam exam = examMapper.selectOne(new LambdaQueryWrapper<Exam>().eq(Exam::getExamId, examDTO.getExamId()));
        if (exam == null) {
            throw new ServiceException(ResultCode.EXAM_NOT_EXISTS);
        }

        //然后检验该exam是否已经开始
        checkExam(exam);

        //然后再去数据库尝试查询用户报名信息
        //获取当前登陆的userId
        Long userId = ThreadLocalUtil.get(TTLConstants.USER_ID,Long.class);

        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>().eq(UserExam::getExamId, examDTO.getExamId())
                .eq(UserExam::getUserId, userId));

        //如果能查到，则说明已经报名，抛出异常
        if (userExam != null) {
            throw new ServiceException(ResultCode.EXAM_NOT_EXISTS);
        }

        //接下来去就真正的报名逻辑
        //首先mysql插入数据
        userExam = new UserExam();
        userExam.setExamId(examDTO.getExamId());
        userExam.setUserId(userId);
        Integer result = userExamMapper.insert(userExam);
        //然后把报名信息存在redis中
        examCacheManger.addUserExamCache(userExam.getExamId(),userExam.getUserId());
        //这里优化了userId的获取方式
        return result;
    }

    //我的竞赛列表

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        //从redis中获取 竞赛列表数据
        Long userId = ThreadLocalUtil.get(TTLConstants.USER_ID,Long.class);
        Long total = examCacheManger.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId);
        List<ExamVO> examVOList;
        if (total == null || total == 0) {
            //如果大小为0，说明缓存中没有数据，需要先从数据库中获取数据
            //从数据库中搜索
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            System.out.println(userExamMapper.selectUserExamList(userId));
            examVOList = userExamMapper.selectUserExamList(userId);
            //然后再刷新缓存
            examCacheManger.refreshCache(ExamListType.USER_EXAM_LIST.getValue(),userId);
            total = new PageInfo<>(examVOList).getTotal();
        }else{
            //如果不为0，则直接redis中查询数据
            examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
            examVOList = examCacheManger.getExamVOList(examQueryDTO,userId);
            total = examCacheManger.getListSize(examQueryDTO.getType(),userId);
        }

        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList,total);
    }

    //检查竞赛是否已经开始
    private void checkExam(Exam exam){
        if (exam.getStartTime().isBefore(LocalDateTime.now())) {
            throw  new ServiceException(ResultCode.EXAM_STARTED);
        }
    }
}
